from flask import Flask, render_template, request
from flask_socketio import SocketIO
import logging

app = Flask(__name__)

# 使用环境变量中的SECRET_KEY（如果设置了的话），否则使用默认值
app.config['SECRET_KEY'] = app.config.get('SECRET_KEY') or 'secret!'

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

socketio = SocketIO(app)

# 定义一个函数来将数据保存到文件
def save_data_to_file(data, filename="data.txt"):
    try:
        with open(filename, "a") as file:
            file.write(f"{data}\n")
    except Exception as e:
        logger.error(f"Failed to write data to file: {e}")


@app.route('/')
def index():
    return render_template('weq.html')


@socketio.on('message')
def handle_message(data):
    logger.info(f"Received message: {data}")
    save_data_to_file(data)
    socketio.emit('response', data, broadcast=True)


if __name__ == '__main__':
    # 注意：在生产环境中应该移除 debug 和 allow_unsafe_werkzeug
    socketio.run(app, debug=True, allow_unsafe_werkzeug=True)